$(function(){
    var _form 		= null;
    var _iduser 	= 0;
    var _mode 		= 'insert';
    var _idusers 	= Array();
    var _idT 		= "";
    var _itemAll 	= null;
	
    disabledControls(true);
	
    if(_intUserT!=1) {
        _idT = 'id='+_intUserI+'&';
        $('#sdelete').css( {
            display:'none'
        } );
        $('#sinsert').css( {
            display:'none'
        } );
    }
	
    $("#jqGrid").jqGrid({
        // <MODIFICAR>
        url: './Queries/query-users.php?'+_idT+'nd='+new Date().getTime(),
        colNames:['int_id_user', 'Identifiant', 'Email', 'Login', 'Modifi&eacute; le', 'Statut', 'Sections', 'Etat', 'Estado'],
        colModel:[
        {
            hidden:true, 
            search:false, 
            name:'int_id_user', 
            index:'int_id_user', 
            align:'left'
        },

        {
            name:'var_fullname', 
            index:'var_fullname', 
            align:'left'
        },

        {
            name:'var_email', 
            index:'var_email', 
            align:'left'
        },

        {
            name:'var_username', 
            index:'var_username', 
            align:'left'
        },

        {
            name:'dat_modification', 
            index:'dat_modification', 
            align:'center'
        },

        {
            name:'var_desc_typeuser', 
            index:'var_desc_typeuser', 
            align:'left'
        },

        {
            name:'var_desc_section', 
            index:'var_desc_section', 
            aligns:'left'
        },

        {
            search:false, 
            name:'var_htmldesc', 
            index:'var_htmldesc', 
            align:'left'
        },

        {
            hidden:true, 
            name:'var_state_description', 
            index:'var_state_description', 
            align:'left'
        }
        ],
        sortname: ['int_id_user','var_desc_typeuser','var_desc_section'],
        sortorder: "asc",
        width: 938,
        height: 400,
        // </MODIFICAR>
		
        loadtext: 'Chargement..',
        datatype: "json",
        pager: '#jqpager',
        rowNum:50,
        rowList:[10,20,50],	
        viewrecords: true,
        multiselect: true
    });
		
    function validateform(){
        $('#txtnombre').select();
        _form = $("#frmnuevousuario").validate({
            event: "blur",
            rules:{ 
                'txtusuario': {
                    required: true, 
                    minlength: 6
                },
                'txtnombre': {
                    required: true, 
                    minlength: 6
                },
                'txtemail': {
                    required: true, 
                    minlength: 6
                },
                'txtclave': {
                    required: true, 
                    minlength: 6
                },
                'cboseccion': "required",
                'cbotipousuario': "required",
                'cboestado': "required"	
            },
            messages:{
                'txtusuario': "Entrez votre login, minimum de 6 caract&egrave;res.",
                'txtnombre': "Entrez votre identifiant.",
                'txtemail': "Entrez votre e-mail.",
                'txtclave': "Entrez votre mot de passe, minimum de 6 caract&egrave;res.",
                'cboseccion': "S&eacute;lectionner la section.",
                'cbotipousuario': "S&eacute;lectionner votre statut.",
                'cboestado': "S&eacute;lectionner votre &eacute;tat"
            }
        });	
		
        // SAVE FORM
        $("#frmnuevousuario").submit(function(){
            if(_form.valid()){
                disabledControls(false);
                save_nuevo();
                disabledControls(true);
            }
			
            return false;
        });
    }
	
    //    $('#jqGrid').navGrid('#jqpager', {
    //        search:false, 
    //        add:false,
    //        del:false,
    //        edit:false
    //    });
	
	
    $("#supdate").click(function(){
        _mode = 'update';
        var s = $("#jqGrid").getIdsArray();
        switch(s.length){
            case 0:
                messageBox('Avertissement','S&eacute;lectionner un utilisateur parmi la liste.',"alert");
                break;
			
            case 1:
                _iduser = s[0];
                disabledControls(false);
                getUser( _iduser );
                ShowForm();
                break;
			
            default:
                messageBox('Avertissement','Modifier seulement un utilisateur &agrave; la fois.',"alert");
                break;
        }
    });
	
    $("#sdelete").click(function(){
        if(_intUserT == 1){
            _mode = 'delete';
            var gr = $("#jqGrid").getGridParam('selrow');
	
            if( gr != null ) 
            {
                var s = $("#jqGrid").getIdsArray('selarrrow');
                var f = s.toString();
                var j =  f.split(',');
                _idusers = j;
                messageBoxConfirm("Eliminer l'utilisateur", 'Vous avez selection&eacute; '+j.length+" utilisateur(s).<br/>Voulez vous vraiment l'effacer(s)?", "alert");
            }
            else{
                messageBox('Avertissement','S&eacute;lectioner les utilisateurs &agrave; effacer.',"alert");
            }
        }
    });
	
    $("#sinsert").click(function(){
        _mode = 'insert';
        if(_intUserT == 1){
            disabledControls(false);
            ShowForm();
        }
    });
	
    $("#cbotipousuario").change(function(){
        if($(this).val()==1){
            if(_itemAll!=null) $("#cboseccion").prepend('<option value="1">All</option>');
            selectCbo( "#cboseccion", 1);
            selectCbo( "#cboestado", 1);
			
            $("#cboseccion").attr('disabled','-1'); 
            $("#cboestado").attr('disabled','-1'); 
        }
        else{
            $("#cboseccion").removeAttr('disabled');
            $("#cboestado").removeAttr('disabled');
            deleteItem( "#cboseccion", 1 );
            selectCbo( "#cboseccion", 0);
            selectCbo( "#cboestado", 0);
        }
    });
	
    function deleteItem(_idcbo,_intval){
        $(_idcbo+" option").each(function(){
            if($(this).val() == _intval){
                _itemAll = $(this);
                $(this).remove(); 
            }
        });
    }
	
    $('#s-dialog-cancelar4').click(function(){
        deleteUsers();
    });
	
    function deleteUsers(){
		
        var _newdata = "";
        for(var i = 0; i<_idusers.length; i++){
            _newdata += _idusers[i]+'-';
        }
		
        $.post("./?ws=User&act=deleteUsers", {
            _ids: _newdata, 
            nocache: Math.random()
        }, function(data){
			
            if(data!="" || data!=" "){
                $('#jqGrid').trigger('reloadGrid');
                alert( $.trim(data) );
                $.modal.close();
            }
			
            $("#login-msg").ajaxError(function(request, settings){ 
                alert(settings.url );
            });
        });
    }
	
	
    function ShowForm(){
        if(_mode=='insert') $('#frm-title').html( "Ajouter un utilisateur" );
        else $('#frm-title').html( "Modifier utilisateur" );
						
        $("#msg-nuevo").modal({
            position: [0,0],
            opacity: 45,
            autoResize: true,
            onOpen: function (dialog){
                dialog.overlay.fadeIn('fast', function (){
                    dialog.container.fadeIn('fast', function (){
                        dialog.data.show();
                        validateform();
                    });
                });
            }			
        });	
    }
	
    function messageBox(_title, _msg, _type){
        var _src = './Resouces/images/alert.png';
        switch(_type){
            case "error":
                _src = './Resouces/images/error.png';
                break;
            case "info":
                _src = './Resouces/images/info.png';
                break;
        }
		
        $('#s-dialog-cancelar4').css( {
            display:'none'
        } );
        $('#s-dialog-cancelar3').val( 'Accepter' );
        $('#msg-title').html( _title );
		
        $('#msg-image').attr( 'src', _src );
        $('#msg-text').html( _msg );
		
        $("#msg-alert").modal({
            position: [0,0],
            opacity: 45,
            autoResize: true,
            onOpen: function (dialog){
                dialog.overlay.fadeIn('fast', function (){
                    dialog.container.fadeIn('fast', function (){
                        dialog.data.show();
                    });
                });
            }			
        });
    }

    function messageBoxConfirm(_title, _msg, _type){
        var _src = './Resouces/images/alert.png';
        switch(_type){
            case "error":
                _src = './Resouces/images/error.png';
                break;
            case "info":
                _src = './Resouces/images/info.png';
                break;
        }
		
        $('#msg-title').html( _title );
        $('#s-dialog-cancelar4').css( {
            display:'inline'
        } );
        $('#s-dialog-cancelar3').val( 'Annuler' );
		
        $('#msg-image').attr( 'src', _src );
        $('#msg-text').html( _msg );
		
        $("#msg-alert").modal({
            position: [0,0],
            opacity: 45,
            autoResize: true,
            onOpen: function (dialog){
                dialog.overlay.fadeIn('fast', function (){
                    dialog.container.fadeIn('fast', function (){
                        dialog.data.show();
                    });
                });
            }			
        });
    }
	
    $("#s-dialog-cancelar2").click(function(){
        $.modal.close();
    });
	
    $("#s-dialog-cancelar3").click(function(){
        $.modal.close();
    });
			
    function disabledControls(val){
        if(val){
            $('#txtusuario').attr('disabled','-1'); 
            $('#txtnombre').attr('disabled','-1');
            $('#txtemail').attr('disabled','-1');
            $('#txtclave').attr('disabled','-1');
            $('#cboseccion').attr('disabled','-1');			
            $('#cbotipousuario').attr('disabled','-1'); 
            $('#cboestado').attr('disabled','-1');
            $('#btnguardar').attr('disabled','-1');
        }
        else{
            $('#txtusuario').removeAttr('disabled'); 
            $('#txtnombre').removeAttr('disabled');
            $('#txtemail').removeAttr('disabled');
            $('#txtclave').removeAttr('disabled');

            if(_intUserT == 1){
                $('#cboseccion').removeAttr('disabled');
                $('#cbotipousuario').removeAttr('disabled'); 
                $('#cboestado').removeAttr('disabled');
            }
			
            $('#btnguardar').removeAttr('disabled');
        }
    }
			
    function save_nuevo(){
        var _funct = 'SaveUser';
		
        if(_mode == 'update'){
            _funct = 'SaveUserUpdate';
        }
		
        $.post("./?ws=User&act="+_funct, {
            _id: _iduser, 
            txtnombre: $('#txtnombre').val(),
            txtemail: $('#txtemail').val(),
            txtusuario: $('#txtusuario').val(), 
            txtclave:$('#txtclave').val(), 
            cboseccion: $('#cboseccion').val(), 
            cbotipousuario: $('#cbotipousuario').val(), 
            cboestado: $('#cboestado').val(), 
            nocache: Math.random()
        }, function(data){
			
            if(data!="" || data!=" "){
                $('#jqGrid').trigger('reloadGrid');
                alert( $.trim(data) );
                $.modal.close();
            }
			
            $("#login-msg").ajaxError(function(request, settings){ 
                alert(settings.url );
            });
        });
    }
	
    function getUser(_id){
        $.post("./?ws=User&act=getUserById", {
            _id:_id, 
            nocache: Math.random()
        }, function(data){
            $(".submitimagehidden").ajaxSuccess(function(evt, request, settings) { 
				
                })
                
            if(data!="" || data!=" "){
                var _data = Array();
                _data = data.split('_%_');
                $('#txtnombre').val( $.trim( _data[0] ) ); 
                $('#txtemail').val( $.trim( _data[1] ) ); 
                $('#txtusuario').val( $.trim( _data[2] ) ); 
                $('#txtclave').val( $.trim( _data[3] ) ); 
                selectCbo('#cboseccion', _data[4]);
                selectCbo('#cbotipousuario', _data[5]);
                selectCbo('#cboestado', _data[6]);
				
                if($("#cbotipousuario").val()==1){
                    if(_itemAll!=null){
						
                        var _ex = false;
                        $("#cbotipousuario option").each(function (){
                            if($(this).val() == 1){
                                _ex = true;
                            }
                        });
						
                        if(!_ex) $("#cboseccion").prepend( '<option value="1">All</option>' );
                    }
                    $('#cboseccion').attr('disabled','-1'); 
                    $('#cboestado').attr('disabled','-1');
                }				
                else{
                    deleteItem( "#cboseccion", 1 );
                }
            }
			
            $("#login-msg").ajaxError(function(request, settings){ 
                //$(this).html( "Error requesting page " + settings.url );
                });
			
            $(".submitimagehidden").ajaxSend(function(evt, request, settings){				  
				
                }); 
        });
    }
	
    function selectCbo(_idcbo, _intval){
        $(_idcbo+" option").each(function (){
            if($(this).val() == _intval){
                $(this).attr('selected','selected'); 
            }
        });
    }
	
});
